﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WFNetLib.TCP;
using WFNetLib.PacketProc;
using WFNetLib.MyControls;
using WFNetLib.Net;
using 数据函数库;
using WFNetLib;
using System.Threading;
using System.Net;
using System.Diagnostics;
using System.Collections;

namespace 温室大棚
{
    public partial class Form1 : Form
    {
        Hashtable CurGreenhouseList;
        public Form1()
        {
            InitializeComponent();
            tcpAsyncServer = new TCPAsyncServer();
            //tcpAsyncServer.TCPServerName = "192.168.1.104";
            tcpAsyncServer.TCPServerPort = 9000;
            tcpAsyncServer.SaveDataProcessCallback = new SaveDataProcessCallbackDelegate(TcpPacket.SaveDataProcessCallbackProc);
            tcpAsyncServer.ErrorServerEvent+=new TCPErrorEvent(tcpAsyncServer_ErrorServer);
            tcpAsyncServer.AcceptServerEvent+=new TCPAcceptEvent(tcpAsyncServer_AcceptServer);
            tcpAsyncServer.DisconnectServerEvent+=new TCPDisconnectEvent(tcpAsyncServer_DisconnectServer);
            tcpAsyncServer.ReceiveServerEvent+=new TCPReceiveEvent(tcpAsyncServer_ReceiveServerEvent);
            CurGreenhouseList = new Hashtable();
            timer1.Enabled = true;
        }
        TCPAsyncServer tcpAsyncServer;
        bool bWait;
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (toolStripButton1.Text == "启动服务器")
            {
                toolStripButton1.Text = "停止服务器";
                tcpAsyncServer.Start();
            }
            else
            {
                toolStripButton1.Text = "启动服务器";
                tcpAsyncServer.Stop();
            }
        }
        private void tcpAsyncServer_ReceiveServerEvent(object sender, ReceiveServerEventArgs e)
        {
            GreenhouseInfo gf;
            this.Invoke((EventHandler)(delegate
            {
                try
                {
                    TcpPacket[] rxList = (TcpPacket[])e.netPacket;
                    foreach (TcpPacket rx in rxList)
                    {
                        textBox1.AppendText(WFNetLib.Strings.StringsFunction.byteToHexStr(rx.AllData, " ") + "\r\n");
                        Debug.WriteLine(WFNetLib.Strings.StringsFunction.byteToHexStr(rx.AllData, " "));
                        switch (rx.Header.Command)
                        {
                            case 1:
                                实时数据Data ssData = DataAnalysis.实时数据DataAnalysis(rx);
                                ssData.IP = ((IPEndPoint)e.Client.ClientSocket.RemoteEndPoint).Address.ToString();
                                实时数据DataDBOption.Insert(ssData);
                                textBox1.AppendText("收到 大棚号为" + ssData.GreenhouseAddr.ToString() + " 节点号为" + ssData.NoteNum.ToString() + " 的实时数据" + "\r\n");
                                gf = (GreenhouseInfo)CurGreenhouseList[e.Client.key];
                                if (gf != null)
                                {
                                    gf.Update = DateTime.Now;
                                    CurGreenhouseList[e.Client.key] = gf;
                                }
                                else
                                {
                                    gf = new GreenhouseInfo();
                                    gf.ip = e.Client.ClientSocket.RemoteEndPoint.ToString();
                                    gf.GreenhouseAddr = ssData.GreenhouseAddr;
                                    gf.NoteNum = ssData.NoteNum;
                                    CurGreenhouseList.Add(e.Client.key, gf);
                                }
                                break;
                            case 2:
                                大棚信息Data dpData = DataAnalysis.大棚信息DataAnalysis(rx);
                                UInt16 oldGreenhouseAddr = (UInt16)dpData.GreenhouseAddr;
                                byte oldNoteNum = (byte)dpData.NoteNum;
                                UInt16 newGreenhouseAddr = BytesOP.MakeShort(rx.Data[0], rx.Data[1]);
                                byte newNoteNum = (byte)rx.Data[2];
                                textBox1.AppendText("收到 大棚号为" + oldGreenhouseAddr.ToString() + " 节点号为" + oldNoteNum.ToString() + " 的大棚信息数据" + "\r\n");
                                dpData.IP = ((IPEndPoint)e.Client.ClientSocket.RemoteEndPoint).Address.ToString();
                                大棚信息DataDBOption.Update(dpData,newGreenhouseAddr,newNoteNum);  
                                gf = (GreenhouseInfo)CurGreenhouseList[e.Client.key];
                                if (gf != null)
                                {
                                    gf.Update = DateTime.Now;
                                    gf.GreenhouseAddr = newGreenhouseAddr;
                                    gf.NoteNum = newNoteNum;
                                    CurGreenhouseList[e.Client.key] = gf;
                                }
                                else
                                {
                                    gf = new GreenhouseInfo();
                                    gf.ip = e.Client.ClientSocket.RemoteEndPoint.ToString();
                                    gf.GreenhouseAddr = newGreenhouseAddr;
                                    gf.NoteNum = newNoteNum;
                                    CurGreenhouseList.Add(e.Client.key, gf);
                                }
                                rx.Header.GreenhouseAddr = BytesOP.MakeShort(rx.Data[0], rx.Data[1]);
                                rx.Header.NoteNum = rx.Data[2];
                                实时数据DataDBOption.Change大棚信息(dpData.IP, oldGreenhouseAddr,oldNoteNum , newGreenhouseAddr,newNoteNum);
                                传感器阈值DataDBOption.Change大棚信息(dpData.IP, oldGreenhouseAddr, oldNoteNum, newGreenhouseAddr, newNoteNum);
                                远程操作DataDBOption.Change大棚信息(dpData.IP, oldGreenhouseAddr, oldNoteNum, newGreenhouseAddr, newNoteNum); 
                           
                                break;
                            case 3:
                                传感器阈值Data cgqData = DataAnalysis.传感器阈值DataAnalysis(rx);
                                cgqData.IP = ((IPEndPoint)e.Client.ClientSocket.RemoteEndPoint).Address.ToString();
                                传感器阈值DataDBOption.Update(cgqData);
                                textBox1.AppendText("收到 大棚号为" + cgqData.GreenhouseAddr.ToString() + " 节点号为" + cgqData.NoteNum.ToString() + " 的传感器阈值数据" + "\r\n");
                                break;
                            case 4:
                                if (bWait)
                                {
                                    timer2.Enabled = false;
                                    MessageBox.Show("设定成功");
                                    bWait = false;
                                    toolStripButton2.Enabled = true;
                                }
                                break;
                        }
                        if (rx.Header.Command != 4)
                            tcpAsyncServer.Send(e.Client, TcpPacket.MakeTcpPacket(rx.Header.Command, rx.Header.GreenhouseAddr, rx.Header.NoteNum, new byte[2] { 0x4f, 0x4d }));
                    }
                }
                catch (System.Exception ex)
                {
                    textBox1.AppendText("发生错误"+ex.Message);
                }                
            }));
        }     
        private void tcpAsyncServer_ErrorServer(object sender, ErrorServerEventArgs e)
        {
            this.Invoke((EventHandler)(delegate
            {
                textBox1.AppendText(e.Error.Message + "\r\n");

            }));
        }
        private void tcpAsyncServer_AcceptServer(object sender, AcceptServerEventArgs e)
        {
            this.Invoke((EventHandler)(delegate
            {
                IPEndPoint x = (IPEndPoint)e.Client.ClientSocket.RemoteEndPoint;
                ComboBoxItem c = new ComboBoxItem(e.Client.ClientSocket.RemoteEndPoint.ToString(), e.Client.key);
                int i = toolStripComboBox1.Items.Add(c);
                toolStripComboBox1.SelectedIndex = i;
            }));
        }
        private void tcpAsyncServer_DisconnectServer(object sender, DisconnectEventArgs e)
        {
            this.Invoke((EventHandler)(delegate
            {
                foreach (object o in toolStripComboBox1.Items)
                {
                    if (o.ToString() == e.Client.ClientSocket.RemoteEndPoint.ToString())
                    {
                        toolStripComboBox1.Items.Remove(o);
                        break;
                    }
                }
            }));
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text.Length > 32000)
                textBox1.Clear();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            byte[] tx = new byte[4];
            tx[0] = 1;
            tx[1] = 1;
            tx[2] = 1;
            tx[3] = 1;
            byte[] tx1 = TcpPacket.MakeTcpPacket(4, 1, 1, tx);
            ComboBoxItem c = (ComboBoxItem)toolStripComboBox1.SelectedItem;
            tcpAsyncServer.Send(c.Value.ToString(), tx1);
            bWait = true;
            timer2.Enabled = true;
            toolStripButton2.Enabled = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            ArrayList rs = new ArrayList();
            foreach (DictionaryEntry de in CurGreenhouseList)
            {
                GreenhouseInfo gf = (GreenhouseInfo)de.Value;
                if (gf.Update.AddSeconds(120) < DateTime.Now)
                    rs.Add(de.Key);
            }
            foreach (object b in rs)
            {
                CurGreenhouseList.Remove(b);
            }
        }
        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            Form实时数据 f = new Form实时数据();
            tcpAsyncServer.ReceiveServerEvent += new TCPReceiveEvent(f.tcpAsyncServer_ReceiveServerEvent);
            f.ShowDialog();
            tcpAsyncServer.ReceiveServerEvent -= new TCPReceiveEvent(f.tcpAsyncServer_ReceiveServerEvent);
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            Form历史数据 f = new Form历史数据();
            f.ShowDialog();
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            Form远程控制 f = new Form远程控制(CurGreenhouseList,tcpAsyncServer);
            tcpAsyncServer.ReceiveServerEvent += new TCPReceiveEvent(f.tcpAsyncServer_ReceiveServerEvent);
            f.ShowDialog();
            tcpAsyncServer.ReceiveServerEvent -= new TCPReceiveEvent(f.tcpAsyncServer_ReceiveServerEvent);
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            timer2.Enabled = false;
            if (bWait)
            {
                bWait = false;
                MessageBox.Show("设定失败");
                toolStripButton2.Enabled = true;
            }
        }
    }
    public class GreenhouseInfo
    {
        public string ip;
        public int GreenhouseAddr;
        public int NoteNum;
        public DateTime Update;
        public GreenhouseInfo()
        {
            Update = DateTime.Now;
        }
    }
}
